package cn.edu.zut.sunday.config;

import static cn.edu.zut.sunday.constant.BaseConstant.BASE_PACKAGE_NAME;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Slf4j
@EnableSwagger2
@Configuration
public class ViewConfig {

    /**
     * 跨域处理
     */
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig());
        return new CorsFilter(source);
    }

    private CorsConfiguration corsConfig() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOrigin("*");
        configuration.addAllowedHeader("*");
        configuration.addAllowedMethod("*");
        configuration.setAllowCredentials(true);
        configuration.setMaxAge(3600L);
        return configuration;
    }

    /**
     * 创建Swagger2 Api对象
     *
     * @return Swagger2对象
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
          .useDefaultResponseMessages(false)
          .apiInfo(apiInfo())
          .select()
          .apis(RequestHandlerSelectors.basePackage(BASE_PACKAGE_NAME))
          .paths(PathSelectors.any())
          //创建
          .build();
    }

    /**
     * 设置Swagger2-UI展示信息 访问连接：#{http://localhost:8081/swagger-ui/index.html}
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
          .title("Spring MVC-Swagger2集成")
          .description("spring+springmvc+jpa/hibernate | swagger")
          // 作者信息
          .contact(new Contact("sunday小组", "https://www.baidu.com", "hxc@qq.com"))
          .version("1.0")
          .build();
    }
}
